package com.gitee.wsl.android.store.statehandle

import androidx.lifecycle.SavedStateHandle
import com.gitee.wsl.data.store.AbstractStoreServer
import com.gitee.wsl.data.store.StateSavedNullAbleVar
import com.gitee.wsl.data.store.StateSavedVar
import kotlin.reflect.KClass

class StateHandleStoreServer(val state: SavedStateHandle): AbstractStoreServer() {
    override fun <T:Any> getOrNull(key: String, type: KClass<T>): T? {
       return state.get<T>(key)
    }

    override fun <T : Any> realPut(key: String, value: T) {
        state[key]=value
    }

    override fun isExits(key: String): Boolean {
        return state.contains(key)
    }

    override fun realRemove(key: String) {
        state.remove<Any>(key)
    }
}

fun <T : Any> SavedStateHandle.saveAble(key:String, defaultValue:T): StateSavedVar<T> = StateSavedVar(
    StateHandleStoreServer(this), key, defaultValue
)

inline fun <reified T : Any> SavedStateHandle.saveAble(key:String): StateSavedNullAbleVar<T> =
    StateSavedNullAbleVar(StateHandleStoreServer(this), key, null )